package utils

import (
	"archive/zip"
	"io"
	"log/slog"
	"os"
	"path/filepath"
	"strings"
)

// Zip srcFile could be a single file or a directory
func Zip(srcFile string, destZip string) error {
	zipFile, err := os.Create(destZip)
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	defer func(zipFile *os.File) {
		err := zipFile.Close()
		if err != nil {
			slog.Error(err.Error())
		}
	}(zipFile)

	archive := zip.NewWriter(zipFile)
	defer func(archive *zip.Writer) {
		err := archive.Close()
		if err != nil {
			slog.Error(err.Error())
		}
	}(archive)

	err = filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			slog.Error(err.Error())
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			slog.Error(err.Error())
			return err
		}

		header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
		// header.Name = path
		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			slog.Error(err.Error())
			return err
		}

		if !info.IsDir() {
			file, err := os.Open(path)
			if err != nil {
				slog.Error(err.Error())
				return err
			}
			defer func(file *os.File) {
				err := file.Close()
				if err != nil {
					slog.Error(err.Error())
				}
			}(file)
			_, err = io.Copy(writer, file)
			if err != nil {
				slog.Error(err.Error())
				return err
			}
		}
		return nil
	})
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	return nil
}

func Unzip(zipFile string, destDir string) error {
	zipReader, err := zip.OpenReader(zipFile)
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	defer func(zipReader *zip.ReadCloser) {
		err := zipReader.Close()
		if err != nil {
			slog.Error(err.Error())
		}
	}(zipReader)

	for _, f := range zipReader.File {
		dstFilePath := filepath.Join(destDir, f.Name)
		if f.FileInfo().IsDir() {
			err := os.MkdirAll(dstFilePath, os.ModePerm)
			if err != nil {
				slog.Error(err.Error())
				return err
			}
		} else {
			if err = os.MkdirAll(filepath.Dir(dstFilePath), os.ModePerm); err != nil {
				return err
			}
			if err := unzipSubFile(f, dstFilePath); err != nil {
				slog.Error(err.Error())
				return err
			}
		}
	}
	return nil
}

func unzipSubFile(f *zip.File, dstPath string) error {
	inFile, err := f.Open()
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	defer func(inFile io.ReadCloser) {
		err := inFile.Close()
		if err != nil {
			slog.Error(err.Error())
		}
	}(inFile)

	outFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	defer func(outFile *os.File) {
		err := outFile.Close()
		if err != nil {
			slog.Error(err.Error())
		}
	}(outFile)

	_, err = io.Copy(outFile, inFile)
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	return nil
}
